<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item> 采集策略配置</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <el-row style="font-weight: bolder; margin-bottom: 10px"
        >车辆动态配置前后对比（仅显示配置有变化车辆）</el-row
      >
      <div>
        <span>是否全选全部车辆：</span>
        <el-radio-group
          v-model="isAllSelected"
          class="ml-4"
          @change="isAllSelectedChange"
        >
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </div>
      <div v-show="allCar == 0">
        <el-input
          v-model="reqData.vin"
          placeholder="请输入vin号"
          size="small"
          @change="vinChangeFn"
        />
        <el-input
          v-model="reqData.configInfoId"
          placeholder="请输入历史配置方案号"
          size="small"
          @change="configInfoIdChangeFn"
        />

        <el-form
          style="
            border-left: 1px solid #ecedef;
            border-right: 1px solid #ecedef;
            border-top: 1px solid #ecedef;
            border-bottom: 1px solid #ecedef;
          "
        >
          <el-form-item>
            <TableComponent
              ref="tableComponentRef"
              v-loading="isLoading"
              :assetList="advancedTableData"
              :checkBox="true"
              :tableColumns="advancedTableColumns"
              element-loading-text="加载中..."
              @checkSelect="checkSelect"
              @checkSelectAll="checkSelectAll"
            >
              <template #configInfoId="{ row }">
                <span v-if="row.configInfoType === 0"
                  >T{{ row.configInfoId }}</span
                >
                <span v-if="row.configInfoType === 1 && row.configInfoId < 10"
                  >TG00{{ row.configInfoId }}</span
                >
                <span
                  v-if="
                    row.configInfoType === 1 &&
                    row.configInfoId < 100 &&
                    row.configInfoId > 9
                  "
                  >TG0{{ row.configInfoId }}</span
                >
                <span v-if="row.configInfoType === 1 && row.configInfoId > 99"
                  >TG{{ row.configInfoId }}</span
                >

                <span
                  v-else-if="!row.configInfoType && row.configInfoType !== 0"
                  >--</span
                >
              </template>

              <template #vehicleUseType="{ row }">
                <span v-if="row.vehicleUseType === 0">量产车</span>
                <span v-if="row.vehicleUseType === 1">研发车</span>
                <span v-if="row.vehicleUseType === 2">台架</span>
                <span
                  v-else-if="!row.vehicleUseType && row.vehicleUseType !== 0"
                  >--</span
                >
              </template>
              <template #domainControlType="{ row }">
                <span v-if="row.domainControlType === 0">MDC</span>
                <span v-if="row.domainControlType === 1">TDA4</span>
                <span v-if="row.domainControlType === 2">J3</span>
                <span
                  v-else-if="
                    !row.domainControlType && row.domainControlType !== 0
                  "
                  >--</span
                >
              </template>
              <template #version="{ row }">
                <span v-if="row.version">V{{ row.version }}</span>
                <span v-else-if="!row.version">--</span>
              </template>
            </TableComponent>

            <el-pagination
              v-model:page-size="requirePageData.size"
              :currentPage="requirePageData.current"
              :page-sizes="[10, 20, 30, 40, 50]"
              :total="requirePageData.total"
              background
              layout="total, sizes, prev, pager, next, jumper"
              style="margin-top: 20px; float: right"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            >
            </el-pagination>
          </el-form-item>
        </el-form>
      </div>
      <el-form
        style="
          border-left: 1px solid #ecedef;
          border-right: 1px solid #ecedef;
          border-top: 1px solid #ecedef;
          border-bottom: 1px solid #ecedef;
          margin-top: 20px;
        "
      >
        <el-form-item>
          <el-row style="height: 15px; padding-top: 10px">
            <el-col :span="12" style="padding-left: 15px; padding-right: 10px"
              >申请人：
              <el-input
                v-model="applicant"
                placeholder="请输入人名"
                style="width: 130px"
              ></el-input>
            </el-col>
            <el-col :span="12" style="padding-left: 15px; padding-right: 10px"
              >申请人部门：
              <el-input
                v-model="applicantDepartment"
                placeholder="请输入部门"
                style="width: 500px"
              ></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-divider dashed></el-divider>
        </el-form-item>
        <el-form-item class="el-button-middle">
          <div style="display: flex; justify-content: center">
            <el-button type="primary" @click="prevBtn">上一步</el-button>
            <el-button
              :disabled="!btnPermission['ConfigurationComparison-submitBtn']"
              @click="submitBtn"
              type="primary"
              >提交
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { computed, onMounted, reactive, ref, toRaw, watch } from "vue";
import {
  createNewStrategy,
  getCarLatestConfig,
  createNewStrategyNoTrigger,
} from "@/api/strategyConfig";
import TableComponent from "@/components/TableComponent.vue";
import { advancedTableColumns } from "@/constant/collectionStrategyConfig";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import _ from "lodash";

const $route = useRoute();
const $router = useRouter();
const applicant = ref("");
const isLoading = ref(false);
const applicantDepartment = ref("");
const requirePageData = reactive({
  current: 1,
  size: 10,
  total: 0,
});

const reqData = reactive({
  vehicleUseType: [],
  vehicleType: [],
  domainControlType: [],
  vin: "",
  configInfoId: ''
});
const isAllSelected = ref(false);
const advancedTableData = ref([]);
const totalSize = ref(0);
const vinChangeFn = (val) => {
  reqData.vin = val;
  requirePageData.current = 1;
  getCarLatestConfigFn(requirePageData.size);
};
const configInfoIdChangeFn = (val) => {
  reqData.configInfoId = val;
  requirePageData.current = 1;
  getCarLatestConfigFn(requirePageData.size);
};
let allCar = ref(0); // 全选车辆： 0否 1是
const store = useStore();
const projectObj = computed(() => store.state.projectObj);
const btnPermission = computed(() => store.state.btnPermission);
let projectName = projectObj.value.name;

const pageChecked = reactive({});
const getCarLatestConfigFn = (size = 10) => {
  getCarLatestConfig({
    ...reqData,
    ...requirePageData,
    configInfoId: Number(reqData.configInfoId),
    size: size,
  }).then((res) => {
    if (res.data.code === 200) {
      totalSize.value = res.data.data.total;
      advancedTableData.value = res.data.data.records;
      requirePageData.current = res.data.data.current;
      requirePageData.total = res.data.data.total;

      // if (isAllSelected.value && !pageChecked[res.data.data.current]) {
      //     tableComponentRef.value.checkAll();
      //     pageChecked[res.data.data.current] = true;
      // }

      if (!isAllSelected.value && pageChecked[res.data.data.current]) {
        tableComponentRef.value.clearSelection();
        pageChecked[res.data.data.current] = false;
      }
    }
  });
};

const tableComponentRef = ref(null);
const isAllSelectedChange = (val) => {
  if (val === true) {
    allCar.value = 1;
  } else {
    allCar.value = 0;
    carIds.value = [];
    checkedData.value = [];
    tableComponentRef.value.clearSelection();
    pageChecked[requirePageData.current] = false;
  }
};
const checkedData = ref([]);
const checkSelect = (val, row) => {
  checkedData.value = val;
};
const checkSelectAll = (val) => {
  checkedData.value = val;

};
const handlePageChange = (val) => {
  requirePageData.current = val;
  getCarLatestConfigFn(requirePageData.size);
};
const handleSizeChange = (number) => {
  requirePageData.size = number;
  getCarLatestConfigFn(number);
};

const selectedStrategy = reactive({
  strategyGroupId: "",
  strategyId: "",
});

const reqCheckData = reactive({
  cycle: 0,
  triggerCount: 0,
  collectTimeBefore: 0,
  collectTimeAfter: 0,
  dataPload: 0,
  plogFaultLevel: 0,
  plogLongtermMonitor: 0,
  uploadAllLog: 0,
});

// 非trigger配置的 传参
const reqNoTriggerConfigData = ref([]);
const route = useRoute();
watch(
  () => route.query.id,
  () => {
    // reqData：车辆用途、车型、域控类型
    // reqCheckBoxData：采集时长、采集频次

    try {
      if (route.query.from === "trigger") {
        let routerData = JSON.parse(sessionStorage.getItem("routerPara"));
        applicant.value = JSON.parse(
          localStorage.getItem("userInfo")
        ).employeeId;
        // let dep = JSON.parse(localStorage.getItem('userInfo')).department;
        //
        // applicantDepartment.value = dep.split('/')[1] + ' / ' + dep.split('/')[2];
        applicantDepartment.value = JSON.parse(
          localStorage.getItem("userInfo")
        ).department;

        reqCheckData.cycle = routerData.reqCheckBoxData.cycle;
        reqCheckData.triggerCount = routerData.reqCheckBoxData.triggerCount;
        reqCheckData.collectTimeBefore =
          routerData.reqCheckBoxData.collectTimeBefore;
        reqCheckData.collectTimeAfter =
          routerData.reqCheckBoxData.collectTimeAfter;

        reqCheckData.dataPload = routerData.reqCheckBoxData.dataPload;
        reqCheckData.plogFaultLevel = routerData.reqCheckBoxData.plogFaultLevel;
        reqCheckData.plogLongtermMonitor =
          routerData.reqCheckBoxData.plogLongtermMonitor;
        reqCheckData.uploadAllLog = routerData.reqCheckBoxData.uploadAllLog;
        reqCheckData.canCollect = routerData.reqCheckBoxData.canCollect;
        reqCheckData.ethCollect = routerData.reqCheckBoxData.ethCollect;
        reqCheckData.calibrationCollect =
          routerData.reqCheckBoxData.calibrationCollect;
        reqCheckData.faultCollect = routerData.reqCheckBoxData.faultCollect;
        // reqCheckData.logCollect = routerData.reqCheckBoxData.logCollect;
        reqCheckData.scCollect = routerData.reqCheckBoxData.scCollect;
        reqCheckData.collect = routerData.reqCheckBoxData.collect;
        // reqCheckData.scFlag = routerData.reqCheckBoxData.scFlag;
        reqCheckData.cameraLogCollect =
          routerData.reqCheckBoxData.cameraLogCollect;
        reqCheckData.monitorLogCollect =
          routerData.reqCheckBoxData.monitorLogCollect;
        reqCheckData.desayLogUpload = routerData.reqCheckBoxData.desayLogUpload;
        reqCheckData.desayLogMax = routerData.reqCheckBoxData.desayLogMax;
        reqCheckData.allLogMaxSizeMb =
          routerData.reqCheckBoxData.allLogMaxSizeMb; // 全量日志大小
        reqCheckData.triggerCdnConfig =
          routerData.reqCheckBoxData.triggerCdnConfig;

        selectedStrategy.strategyGroupId = Number(
          routerData.selectedStrategy.groupIds.toString()
        );
        selectedStrategy.strategyId = Number(
          routerData.selectedStrategy.strategyIds.toString()
        );
        if (routerData.reqData) {
          let data = routerData.reqData;
          reqData.vehicleUseType = data.vehicleUseType;
          reqData.vehicleType = data.vehicleType;
          reqData.domainControlType = data.domainControlType;
          getCarLatestConfigFn();
        } else if (routerData.checkedData) {
          advancedTableData.value = routerData.checkedData;
          requirePageData.total = routerData.checkedData.length;
          requirePageData.size = routerData.checkedData.length;
        }
      }
      if (route.query.from === "noTrigger") {
        let recNoTriggerPara = JSON.parse(
          sessionStorage.getItem("NoTriggerRouterPara")
        );
        reqNoTriggerConfigData.value = recNoTriggerPara.config.map((item) => {
          return {
            bizId: item.id,
            fileId: item.fileId || "",
            status: item.status,
          };
        });

        getCarLatestConfigFn();
      }
    } catch (e) {}
  },
  {
    immediate: true,
  }
);

const prevBtn = () => {
  if (route.query.from === "trigger") {
    $router.push("/triggerConfiguration/TriggerStrategyConfiguration");
  }
  if (route.query.from === "noTrigger") {
    $router.push("/triggerConfiguration/NoTriggerStrategyConfiguration");
  }
};
const carIds = ref([]);
const vinLists = ref([]);
const submitBtn = () => {
  let createBy = "";
  let creatorDepartment = "";
  try {
    createBy = JSON.parse(localStorage.getItem("userInfo")).employeeId;
    creatorDepartment = JSON.parse(localStorage.getItem("userInfo")).department;
  } catch (e) {}

  if (isAllSelected.value) {
      checkedData.value = [];
  }
  if (!isAllSelected.value) {
    carIds.value = [];
    vinLists.value = [];
    checkedData.value.forEach((item) => {
      carIds.value.push(item.carId);
      vinLists.value.push(item.vin);
    });
  }
  let resCarIds = [...new Set(carIds.value)];

  if (route.query.from === "trigger") {
    let resVinLists = vinLists.value.join(" , ");
    let newVehicleUseType = reqData.vehicleUseType;
    let vehicleTypeDesc = null;
    if(newVehicleUseType.length !== 1){
      vehicleTypeDesc = '全部车辆'
    }else{
      switch(Number(newVehicleUseType.toString())){
        case 0:
          vehicleTypeDesc = '量产车'
          return
        case 1:
          vehicleTypeDesc = '研发车'
          return
        case 2:
          vehicleTypeDesc = '台架'
          return
      }
    }
    let submitDescription = "是否确认提交配置？";
    if (allCar.value === 0) {
      submitDescription = `<p>当前选择的车辆vin为：<strong>${resVinLists}</strong>，是否确认提交配置？</p>`;
    } else {
      submitDescription = `<p>当前全选了<strong>${projectName}</strong>项目的<strong>${vehicleTypeDesc}</strong>，是否确认提交配置？</p>`;
    }
    ElMessageBox.alert(
      submitDescription,
      "确认提交",

      {
        dangerouslyUseHTMLString: true,
        showCancelButton: true,
        customClass: "myMessageBox",
      }
    ).then(() => {
      createNewStrategy({
        createBy: createBy,
        creatorDepartment: creatorDepartment,
        applicant: applicant.value,
        applicantDepartment: applicantDepartment.value,
        carIds: resCarIds,
        strategyGroupId: selectedStrategy.strategyGroupId,
        strategyId: selectedStrategy.strategyId,
        ...reqCheckData,
        allCar: allCar.value,
        vehicleUseTypeList: reqData.vehicleUseType,
      }).then((res) => {
        let response = res.data.data;
        if (response && response == 1) {
          ElMessage.success("配置更新成功");
        } else {
          ElMessage.error("配置更新失败，请重试");
        }
      });
    }).catch(()=> {})
  }

  if (route.query.from === "noTrigger") {
    createNewStrategyNoTrigger({
      createBy: createBy,
      carIds: resCarIds,
      config: reqNoTriggerConfigData.value
    }).then((res) => {
      let response = res.data.data;
      if (response && response == 1) {
        ElMessage.success("配置更新成功");
      } else {
        ElMessage.error("配置更新失败，请重试");
      }
    });
  }
};
</script>

<style lang="less" scoped></style>
<style lang="less">
.el-message-box.myMessageBox {
    width:50%;
    p {
        word-wrap: break-word;
    }
}
</style>
